<template>
        <n-space vertical>
            <n-form
            ref="formRef"
            :model="model"
            label-placement="left"
            :label-width="100"
            class="setting-cont"
            >
            <n-form-item label="角色名称" >
                <n-input v-model:value="model.roleName" placeholder="请输入角色名称" />
            </n-form-item>
            <n-form-item label="角色代号" >
                <n-input v-model:value="model.role" placeholder="请输入角色代号" />
            </n-form-item>
            <n-form-item label="角色权限" path="uploadValue">
                <n-tree
                    block-line
                    :data="routes[0].children"
                    key-field="path"
                    checkable
                    cascade
                    :default-checked-keys="model.permission"
                    @update:checked-Keys="handelCheck"
                />
            </n-form-item>
            <n-form-item label=" " >
                <n-button :type="!rowData?'primary':'info'" size="medium" @click="handelRole" block>
                    {{ rowData?'修改角色':'新增角色'}}
                </n-button>
            </n-form-item>
            </n-form>
        </n-space>
</template>

<script setup>
import { 
    NButton,
    NInput,
    NSpace, 
    NForm,
    NFormItem,
    NTree,
} from 'naive-ui'
import { ref } from 'vue';
import {routes} from '../../router/index.js'
import { flyroleUpdateApi, flyrolePostApi } from '../../api/user.js';
const model = ref({
   roleName:'',
   role:'',
   permission:[],
})

const formRef = ref(null);
const handelCheck = (keys)=>{
    model.value.permission = keys
}
const emit = defineEmits(['role-list'])
// 录入角色
const handelRole =async ()=>{
    let _id = ''
    if(props.rowData){
        _id = props.rowData._id
        await flyroleUpdateApi(_id,model.value)//编辑
    }else{
        let res = await flyrolePostApi(model.value)//新增
        _id = res.data._id
    }
    emit('role-list',{_id,...model.value})
}

// 接收待编辑数据
const props = defineProps(['rowData'])
if(props.rowData){
    model.value = {...props.rowData}// 深拷贝脱离引用
}


</script>

<style lang="scss" scoped>
.setting-cont{
    padding-right: 50px;
}
</style>